package com.huluobo.mvvmdemo20032.repositionies;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.huluobo.mvvmdemo20032.model.Bean;
import com.huluobo.mvvmdemo20032.model.Product;
import com.huluobo.mvvmdemo20032.request.Request;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lc on 2022/9/28.
 */
public class ShopRepo {
    private MutableLiveData<List<Product>> mutableProductList;

    public LiveData<List<Product>> getProducts() {
        if (mutableProductList == null) {
            mutableProductList = new MutableLiveData<>();
            loadProducts();
        }
        return mutableProductList;
    }

    private void loadProducts() {
        List<Product> productList = new ArrayList<>();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Request.HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Call<Bean> call = retrofit.create(Request.class).getBean();
        call.enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                for (int i = 0; i < response.body().data.size(); i++) {
                    Product product = new Product(response.body().data.get(i).id,
                            response.body().data.get(i).title,
                            response.body().data.get(i).num,
                            true,
                            response.body().data.get(i).pic);
                    productList.add(product);
                }
                mutableProductList.setValue(productList);
            }

            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
                Log.i("TagA", "e:" + t.getMessage());
            }
        });
    }
}
